package com.tingyuge.base.jdk.io.nio.filechannel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xiaodao
 * @version 1.0
 * @description fileChannel读取到buffer
 */
public class FileChannelDemo1 {

    public static void main(String[] args) throws IOException {
        URL resource = FileChannelDemo1.class.getClass().getResource("/");
        System.out.println(resource.getPath());
        RandomAccessFile accessFile = new RandomAccessFile(resource.getPath()+"01.txt", "r");
        FileChannel channel = accessFile.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        int read = channel.read(byteBuffer);

        while (read != -1) {
            System.out.println("读取了" + byteBuffer);
            byteBuffer.flip();

            while (byteBuffer.hasRemaining()) {
                System.out.println((char) byteBuffer.get());
            }
            byteBuffer.clear();
            read = channel.read(byteBuffer);
        }
        accessFile.close();
        System.out.println(
                "end"
        );
    }
}
